import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_ywt/config/environment_manager.dart';
import 'package:flutter_ywt/constant/app_data.dart';
import 'package:flutter_ywt/utils/toast_util.dart';
import 'package:logger/logger.dart';

import 'http_base.dart';

final Http _yhHttp = Http();

///错误回调
class HttpCallback {
  DioError onError;

  Map get data {
    return {"dioError": onError};
  }

  HttpCallback(this.onError);
}

///通用的http
class Http extends BaseHttp {
  static final baseUrl = Environment.baseUrl;
  @override
  void init() {
    options.baseUrl = baseUrl;
    interceptors..add(ApiInterceptor());
  }
}

//get请求方法
yhGet(url, {data, options, cancelToken}) async {
  Response response;
  try {
    response = await _yhHttp.get(url,
        queryParameters: data, options: options, cancelToken: cancelToken);
  } on DioError catch (e) {
    toastUtil(e.message);
    print('getHttp exception: $e');
    return HttpCallback(e);
  }
  return response;
}

//post请求
yhPost(url, {data, options, cancelToken}) async {
  Response response;
  try {
    response = await _yhHttp.post(url,
        data: data, options: options, cancelToken: cancelToken);
  } on DioError catch (e) {
    toastUtil(e.response.toString());
    print('postHttp exception: $e');
    return HttpCallback(e);
  }
  return response;
}

//请求拦截器
class ApiInterceptor extends InterceptorsWrapper {
  Logger logger = Logger();

  @override
  Future onRequest(RequestOptions options) {
    //每次请求，携带token
    Map<String, dynamic> header = options.headers;
    header["token"] = AppData.token;

    logger.d("request----->${options.baseUrl + options.path + " " + header.toString()}");
    if (options.queryParameters.isNotEmpty) {
      logger.d("request--get--->${options.queryParameters.toString()}");
    }
    if (options.data != null) {
      logger.d("request--post--->${options.data.toString()}");
    }
    return super.onRequest(options);
  }

  @override
  Future onError(DioError err) {
    return super.onError(err);
  }

  @override
  Future onResponse(Response response) {
    var statusCode = response.statusCode;
    logger.d("response---->${"statusCode= " + statusCode.toString() + " "}  ${response.data}");

    if (statusCode == 200) {
      if (response.data is Map) {
        RespData respData = RespData.fromJson(response.data);
        if (respData.getSuccess()) {
          //取出data，并返回
          response.data = respData.data;
          return Future.value(response);
        } else {
          return handleFailed(respData);
        }
      } else {
        RespData apiResult = RespData.fromJson(jsonDecode(response.data));
        return handleFailed(apiResult);
      }
    } else {
      return Future.value(response);
    }
  }

  Future<Response> handleFailed(RespData respData) {
    logger.e('---请求接口---->error------>$respData');
    if (respData.code == -1001) {
      throw const UnAuthorizedException();
    }
    throw NotSuccessException.fromRespData(respData);
    // return http.reject(respData.message);
  }
}

void formatError(DioError e) {
  if (e.type == DioErrorType.CONNECT_TIMEOUT) {
    print("连接超时");
  } else if (e.type == DioErrorType.SEND_TIMEOUT) {
    print("请求超时");
  } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
    print("响应超时");
  } else if (e.type == DioErrorType.RESPONSE) {
    print("出现异常");
  } else if (e.type == DioErrorType.CANCEL) {
    print("请求取消");
  } else {
    print("未知错误");
  }
}

///处理多种情况，返回的成功标示
class RespData extends BaseRespData {
  bool getSuccess() => success || 200 == code || 0 == code;

  RespData.fromJson(Map<String, dynamic> map) {

    code = map['errorCode'] ?? map['code'] ;
    message = map['errorMsg'];
    data = map['data'];
    if (map.containsKey('success')) {
      success = map['success'];
    }
  }
}
